package com.chmingx.base.handler;

import com.chmingx.base.exception.SchoolException;
import com.chmingx.utils.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 全局异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody // 为了能够返回数据
    public CommonResponse<String> error(Exception e) {
        CommonResponse<String> response = CommonResponse.error();
        response.setMsg(e.getMessage());
        return response;
    }

    /**
     * 特定异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public CommonResponse<String> errorArithmetic(Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        CommonResponse<String> response = CommonResponse.error();
        response.setMsg(e.getMessage());
        return response;
    }

    /**
     * 自定义异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(SchoolException.class)
    @ResponseBody
    public CommonResponse<String> errorSchoolCustomer(SchoolException e) {
        e.printStackTrace();
        CommonResponse<String> response = CommonResponse.error();
        response.setMsg(e.getMsg());
        return response;
    }
}
